package io.renren.modules.haiyou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.haiyou.dao.MerchantApplyDao;
import io.renren.modules.haiyou.entity.Merchant;
import io.renren.modules.haiyou.entity.MerchantApply;
import io.renren.modules.haiyou.service.MerchantApplyService;
import io.renren.modules.haiyou.service.MerchantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Map;


@Service("merchantApplyService")
public class MerchantApplyServiceImpl extends ServiceImpl<MerchantApplyDao, MerchantApply> implements MerchantApplyService {

    @Autowired
    private MerchantService merchantService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MerchantApply> page = this.page(
                new Query<MerchantApply>().getPage(params),
                new QueryWrapper<MerchantApply>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(MerchantApply entity) {
        entity.setId(IdWorker.getIdStr());
        entity.setApplyTime(LocalDateTime.now());
        return SqlHelper.retBool(baseMapper.insert(entity));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(MerchantApply entity) {
        if (entity.getState() == 1) {
            // 申请成功
            // 1.新增一个商家
            Merchant merchant = new Merchant();
            merchant.setPhone(entity.getPhone());
            merchant.setMainProductTypesSold(entity.getMainProductTypesSold());
            merchant.setUserId(entity.getUserId());
            merchant.setStoreName(entity.getStoreName());
            merchant.setStoreAddress(entity.getStoreAddress());
            merchantService.save(merchant);
            // 2.修改申请状态
            entity.setState(1);
        }
        return SqlHelper.retBool(baseMapper.updateById(entity));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return false;
        }
        return SqlHelper.retBool(baseMapper.deleteBatchIds(idList));
    }

}